package com.ahwei.common.rest.feign;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * <p>
 * 这是一个Java文件！
 * </p>
 *
 * @author ahWei
 * @email：ahwei163@qq.com
 * @since 2022-06-10 16:51:18
 */
@Configuration
@Slf4j
public class FeignRequestInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate template) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        // 获取原请求头
        Map<String, String> headers = getHeaders(request);

        // 传递所有请求头，防止部分丢失
        // 此处也可以只传递认证的header
        //requestTemplate.header("Authorization", request.getHeader("Authorization"));
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            template.header(entry.getKey(), entry.getValue());
        }
        log.debug("FeignRequestInterceptor:{}", template.toString());
    }



    /**
     * 获取原请求头
     * @param request .
     * @return .
     */
    private Map<String, String> getHeaders(HttpServletRequest request) {
        Map<String, String> map = new LinkedHashMap<>();
        Enumeration<String> enumeration = request.getHeaderNames();
        if(enumeration!=null){
            while (enumeration.hasMoreElements()) {
                String key = enumeration.nextElement();
                String value = request.getHeader(key);
                map.put(key, value);
            }
        }
        return map;
    }
}